import React, { Component } from "react";

export default class Message extends Component {
  //声明状态
  state = {
    msgs: [1, 2, 3],
  };

  send = () => {
    //获得 input 框的输入内容
    let v = this.input.value;
    //更新 msgs 的状态
    this.setState({
      msgs: [...this.state.msgs, v],
    });
  };

  render() {
    return (
      <div>
        <input type="text" ref={(el) => (this.input = el)} />
        <button onClick={this.send}>发送</button>
        <hr />
        <div
          ref={el => this.result = el}
          id="result"
          style={{
            border: "solid 1px #666",
            padding: 10,
            width: 400,
            height: 200,
            overflowY: "scroll",
          }}
        >
          <ul>
            {this.state.msgs.map((item, index) => {
              return <li key={index}>{item}</li>;
            })}
          </ul>
        </div>
      </div>
    );
  }

  componentDidUpdate(){
    //更新 result 元素的垂直滚动高度
    this.result.scrollTop = this.result.scrollHeight;
  }
}
